package fi.helsinki.cs.ohtu10k.view;

import javax.swing.*;
import java.awt.event.*;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import com.sun.java.layout.SpringUtilities;

import fi.helsinki.cs.ohtu10k.schedule.*;

/**
 * Class implementing add event dialog.
 * @author Hannu Kärnä
 * @author Thomas Nyman
 */
@SuppressWarnings("serial")
public class AddEventDialog extends JDialog implements ActionListener {
	
	private JPanel panel;
	private JButton buttonAddEvent, buttonCancel;
	private JCheckBox checkboxRepeated, checkboxImportant;
	private DateSelector selectorStartDate;
	private TimeSelector selectorStartTime;
	private DurationSelector selectorDuration;
	private JComboBox selectorWeekDay, selectorCourse, selectorEventType;
	
	/**
	 * Displays add event dialog.
	 * @param owner Owning frame.
	 */
	public static void showNewEventDialog(JFrame owner) {
		new AddEventDialog(owner);
	}
	
	/**
	 * Creates a new add event dialog.
	 * @param owner Owning frame.
	 */
	public AddEventDialog(JFrame owner){
		super(owner, Constants.LABEL_ADD_EVENT_TITLE, true);
		
		panel = new JPanel();
		panel.setLayout(new SpringLayout());
		
		// Initialization of interactive components.
		checkboxRepeated = new JCheckBox(Constants.LABEL_ADD_EVENT_REPEATED);
		checkboxRepeated.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
            	if(checkboxRepeated.isSelected()){
            		selectorWeekDay.setEnabled(true);
            		selectorStartDate.setEnabled(false);
            	}
            	else {
            		selectorWeekDay.setEnabled(false);
            		selectorStartDate.setEnabled(true);
            	}
            }
		});
		
		checkboxImportant = new JCheckBox(Constants.LABEL_ADD_EVENT_IMPORTANT);
		
		selectorWeekDay = new JComboBox(Constants.WEEKDAYS);
		selectorWeekDay.setEnabled(false);
		
		selectorStartDate = new DateSelector();		
		
		selectorCourse = new JComboBox(ScheduleManagerHandler.getScheduleManager().getCourses());
		selectorCourse.insertItemAt(Constants.LABEL_ADD_EVENT_NO_COURSE, 0);
		selectorCourse.setSelectedIndex(0);
		
		selectorEventType = new JComboBox(Constants.EVENT_TYPES);		
		selectorStartTime = new TimeSelector();
		selectorDuration = new DurationSelector();
		
		buttonAddEvent = new JButton(Constants.LABEL_ADD_EVENT);
		buttonCancel = new JButton(Constants.LABEL_CANCEL);
		
		// Add components to panel.
		panel.add(checkboxRepeated);
		panel.add(checkboxImportant);
		panel.add(new JLabel(Constants.LABEL_ADD_EVENT_REPEATING_WEEKDAY));
		panel.add(selectorWeekDay);
		panel.add(new JLabel(Constants.LABEL_ADD_EVENT_SINGLE_DATE));
		panel.add(selectorStartDate);
		panel.add(new JLabel(Constants.LABEL_ADD_EVENT_COURSE));
		panel.add(selectorCourse);
		panel.add(new JLabel(Constants.LABEL_ADD_EVENT_TYPE));
		panel.add(selectorEventType);
		panel.add(new JLabel(Constants.LABEL_ADD_EVENT_TIME));
		panel.add(selectorStartTime);
		panel.add(new JLabel(Constants.LABEL_ADD_EVENT_DURATION));
		panel.add(selectorDuration);
		panel.add(new JPanel());
		panel.add(new JPanel());
		panel.add(buttonAddEvent);
		panel.add(buttonCancel);
		
		// Build compact layout
		SpringUtilities.makeCompactGrid(panel,
										9, 2,	//rows, columns
                						18, 12,	//initX, initY
                						18, 12);//xPad, yPad
		
		buttonAddEvent.addActionListener(this);
		buttonCancel.addActionListener(this);
		
		setContentPane(panel);
		pack();
        setLocationRelativeTo(owner);
        setVisible(true);
	}
	
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==buttonAddEvent) {
			
			DateTime startDate = selectorStartTime.getTimeAtDate(selectorStartDate.getDate());
			Duration duration = selectorDuration.getDuration();
			ScheduleCourse scheduleCourse = (selectorCourse.getSelectedIndex() == 0 ? null : (ScheduleCourse)selectorCourse.getSelectedItem());
			
			if(selectorCourse.getSelectedIndex() == 0 && checkboxRepeated.isSelected()){
				JOptionPane.showMessageDialog(this,
					    					  Constants.LABEL_ERROR_NO_COURSE_SELECTED,
					    					  Constants.LABEL_ERROR,
					    					  JOptionPane.ERROR_MESSAGE);
			} else if (duration.equals(Constants.ZERO_DURATION)) {
				JOptionPane.showMessageDialog(this,
  					  						  Constants.LABEL_ERROR_ZERO_DURATION,
  					  						  Constants.LABEL_ERROR,
  					  						  JOptionPane.ERROR_MESSAGE);
			} else {	
				if(checkboxRepeated.isSelected()) {
					int weekday = selectorWeekDay.getSelectedIndex()+1;
					DateTime courseStartDate = scheduleCourse.getStartDate();
					
					startDate = ((courseStartDate.isBefore( courseStartDate.dayOfWeek().setCopy(weekday) ) 
								|| courseStartDate.equals( courseStartDate.dayOfWeek().setCopy(weekday) )) ? 
										courseStartDate.withDayOfWeek(weekday) : 
										courseStartDate.plusWeeks(1).withDayOfWeek(weekday));
					
					startDate = selectorStartTime.getTimeAtDate(startDate);
					
					while (startDate.isBefore(scheduleCourse.getEndDate())) {
						try {
							ScheduleManagerHandler.getScheduleManager().addEvent(startDate, duration, (String)selectorEventType.getSelectedItem(), scheduleCourse,	checkboxImportant.isSelected());
						} catch (TimeSlotTakenException ex) {}
						startDate = startDate.plusWeeks(1);
					}
					setVisible(false);
				} else {
					try {
						ScheduleManagerHandler.getScheduleManager().addEvent(startDate, duration, (String)selectorEventType.getSelectedItem(), scheduleCourse,	checkboxImportant.isSelected());
						setVisible(false);
					} catch (TimeSlotTakenException ex) {
						JOptionPane.showMessageDialog(this,
		  						  Constants.LABEL_ERROR_TIMESLOT_TAKEN,
		  						  Constants.LABEL_ERROR,
		  						  JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		} else setVisible(false);
    }

}
